package com.atwl.school_system.service.serviceImpl;

import com.atwl.school_system.bean.UserInfo;
import com.atwl.school_system.mapping.UserDao;
import com.atwl.school_system.service.UserService;
import com.atwl.school_system.util.R;
import com.sun.org.apache.xpath.internal.operations.Bool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.UUID;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public R login(String phone, String password) {
        UserInfo userInfo = userDao.getUserByName(phone);
        if (userInfo == null) {
            return R.error("用户不存在");
        } else {
            String pwdMd5 = DigestUtils.md5DigestAsHex((password).getBytes());
            if (pwdMd5.equals(DigestUtils.md5DigestAsHex((userInfo.getPassword()).getBytes()))) {
                return R.ok().setData(userInfo);
            } else {
                return R.error("密码错误");
            }
        }
    }

    /*
     private Integer id;
    private String userName;
    private Integer userId;
    private String phone;
    private String password;
    private Date enrollTime;
     */
    @Override
    public R register(String phone, String password, String code) {
        // 校验前端做了，懒得做了
        String userId = UUID.randomUUID().toString().substring(0, 10);
        String username = "游客 " + userId;
        ValueOperations<String, String> redisTmp = stringRedisTemplate.opsForValue();
        String code_redis = redisTmp.get("code");
        if (code_redis == null) {
            return R.error("请先获取验证码");
        }
        if (code.equals(code_redis)) {
            Boolean flag = userDao.register(username, userId, phone, password);
            if (!flag) {
                return R.error("注册失败");
            } else {
                return R.ok("注册成功");
            }
        } else {
            return R.error("验证码不正确");
        }
    }
}
